package com.example.tigering.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * @Author: xwg
 * @CreateDate: 2023/8/23
 */

@Service
public class RedisCodeGenerator implements CodeProducer {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public String nextCode(String prefix) {

        String head = prefix.toUpperCase(Locale.ROOT);
        String body = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String foot = null;

        String key = "TIGER:"+prefix.toUpperCase(Locale.ROOT);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.setIfAbsent(key,"1");
        String s = ops.get(key);
        ops.increment(key);
        foot= String.format("%06d", Integer.valueOf(s));

//        HS 20230628 0001
        return head+body+foot;
    }
}
